import React, { useState } from "react";
import { Card, Button, Input, Space, Divider, Typography, Badge } from "antd";
import { useCounterStore } from "../stores/counterStore";

const { Title } = Typography;

const CounterDisplay: React.FC = () => {
  // 从 store 中获取状态和方法
  const { count, increment, decrement, reset } = useCounterStore();

  return (
    <Card title="计数器组件" bordered={false} className="counter-card">
      <div className="counter-value">
        <Badge
          count={count}
          showZero
          overflowCount={99}
          style={{
            backgroundColor:
              count > 0 ? "#52c41a" : count < 0 ? "#f5222d" : "#1677ff",
            fontSize: "16px",
            padding: "0 8px",
          }}
        />
      </div>
      <Space className="counter-actions">
        <Button onClick={decrement}>减少</Button>
        <Button onClick={reset}>重置</Button>
        <Button type="primary" onClick={increment}>
          增加
        </Button>
      </Space>
    </Card>
  );
};

const TitleEditor: React.FC = () => {
  // 从 store 中获取标题和设置标题的方法
  const { title, setTitle } = useCounterStore();
  const [inputValue, setInputValue] = useState(title);

  const handleTitleChange = () => {
    setTitle(inputValue);
  };

  return (
    <Card title="标题编辑器组件" bordered={false} className="title-card">
      <Space direction="vertical" style={{ width: "100%" }}>
        <Input
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
          placeholder="输入新标题"
        />
        <Button type="primary" onClick={handleTitleChange} block>
          更新标题
        </Button>
      </Space>
    </Card>
  );
};

const Header: React.FC = () => {
  // 只订阅 title
  const title = useCounterStore((state) => state.title);

  return (
    <div className="header-display">
      <Title level={2}>{title}</Title>
      <Badge count="全局状态" style={{ backgroundColor: "#722ed1" }} />
    </div>
  );
};

const ZustandDemo: React.FC = () => {
  return (
    <div className="zustand-demo">
      <Header />

      <Divider />

      <div className="demo-layout">
        <CounterDisplay />
        <TitleEditor />
      </div>

      <Divider orientation="left">状态检查器</Divider>

      <Card title="当前状态" size="small">
        <pre className="state-inspector">
          {JSON.stringify(useCounterStore.getState(), null, 2)}
        </pre>
      </Card>
    </div>
  );
};

export default ZustandDemo;
